<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script lang="ts">
import echarts, { EChartOption, ECharts } from 'echarts'
import { Component, Prop, Watch } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import ResizeMixin from '@/components/charts/mixins/resize'
import MacaronsTheme from '@/components/charts/themes/macarons'

export interface IPieChartData {
  legend: string[]
  series: {
    name: string
    value: number
  }[]
}

@Component({
  name: 'PieAgeChart'
})
export default class extends mixins(ResizeMixin) {
  @Prop({ required: true }) private chartData!: IPieChartData
  @Prop({ default: 'chart' }) private className!: string
  @Prop({ default: '100%' }) private width!: string
  @Prop({ default: '280px' }) private height!: string

  protected chart!: ECharts | null

  @Watch('chartData', { deep: true })
  private onChartDataChange(value: IPieChartData) {
    this.setOptions(value)
  }

  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  }

  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  }

  private initChart() {
    this.chart = echarts.init(this.$el as HTMLDivElement, MacaronsTheme)
    this.setOptions(this.chartData)
  }

  private setOptions(chartData: IPieChartData) {
    if (this.chart) {
      this.chart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {d}%'
        },
        series: [
          {
            top: 50,
            name: '库存',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: chartData.series,
            // data: [
            //   { value: 300, name: '已用' },
            //   { value: 3900, name: '剩余' }
            // ],
            color: ['#E4DBDA', '#FFAA00']
            // itemStyle: {
            //   color: (params: any) => {
            //     // console.log(params.name)
            //     let colorVal = '#E4DBDA'
            //     switch (params.name) {
            //       case '已用':
            //         colorVal = '#E4DBDA'
            //         break
            //       case '剩余':
            //         colorVal = '#FFAA00'
            //         break
            //     }
            //     return colorVal
            //   }
            // }
          }
        ]
      } as EChartOption<any>)
    }
  }
}
</script>
<style lang="scss" scoped>
// .chart {
//   ::v-deep canvas{
//     top: 30px !important;
//   }
// }
</style>
